package zisu.netty.practice.netty.secs;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import zisu.netty.practice.netty.secs.entity.HSMSMessage;

import java.util.Arrays;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/7/29 10:36
 *
 *
 * 数据传递都用byte流好了
 */
public class MyServerHandler extends SimpleChannelInboundHandler<HSMSMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HSMSMessage msg) throws Exception {
        //[-1, -1, 0, 0, 0, 1, 0, 0, 0, 1]
        //[FF, FF, 0, 0, 0, 1, 0, 0, 0, 1 ]
        System.out.println(msg);
        byte sType = msg.getHeader()[5];
        HSMSMessage hsmsMessage = new HSMSMessage();
        if(sType == 1){
            hsmsMessage.setLength(msg.getLength());
            byte[] hh = msg.getHeader();
            hh[5] = 2;
            hsmsMessage.setHeader(hh);
        }else if(sType == 5){
            hsmsMessage.setLength(msg.getLength());
            byte[] hh = msg.getHeader();
            hh[5] = 6;
            hsmsMessage.setHeader(hh);
        }

        byte[] header = hsmsMessage.getHeader();
        byte[] length = hsmsMessage.getLength();
        byte[] content = new byte[14];
        for(int i=0;i<4;i++){
            content[i] = length[i];
        }
        for(int i=0;i<10;i++){
            content[i+4] = header[i];
        }
        System.out.println("发送的byte："+ Arrays.asList(content));

        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeBytes(content);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        //就把上下文所有的连接都关闭
        ctx.close();
    }
}
